package com.heima.kafka.stream;

import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;

@Configuration
public class KafkaStreamHandler {

    @Bean
    public KStream<String,String> kStream(StreamsBuilder streamsBuilder){
        //创建KStream对象，并接收消息
        KStream<String, String> stream = streamsBuilder.stream("itcast-input-topic");

        //流式计算分析
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            @Override
            public Iterable<String> apply(String value) {
                String[] split = value.split(" ");
                return Arrays.asList(split);
            }
        })
                //分组
                .groupBy((key,value)->value)
                //时间窗口，可以设置窗口大小
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                //count之后，key和value会有变化  key:消息的值  vlaue：统计之后的数值
                .count()
                //转换为KStream
                .toStream()
                .map((key,value)->{
                    System.out.println("消息的key:"+key.key().toString()+",value:"+value.toString());
                    return new KeyValue<>(key.key().toString(),value.toString());
                })
                //处理完数据之后，发送给某一个topic
                .to("itcast-out-topic");
        return stream;
    }
}
